<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>找出字符串中第一个匹配项的下标</title>
</head>
<body>
  <script>
    function fn(haystack, needle) {
      const n = haystack.length, m = needle.length;
      for (let i = 0; i + m <= n; i++) {
        let flag = true;
        for (let j = 0; j < m; j++) {
          if (haystack[i + j] != needle[j]) {
            flag = false;
            break;
          }
        }
        if (flag) {
          return i
        }
      }
      return -1
    }
    console.log(fn('sadbutsad', 'sad'))
  </script>
</body>
</html>